/**
 * $Id$ Copyright 2009-2012 Oak Pacific Interactive. All rights reserved.
 */
package com.shuqi.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.shuqi.activity.adapter.BookDownloadAdapter;
import com.shuqi.activity.viewport.BottomDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.EnterBookContent;
import com.shuqi.common.NetNotify;
import com.shuqi.common.utils.Log4an;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.TxtDownloadDao;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.database.model.TxtDownload;
import com.shuqi.model.manager.BookMarkManager;
import com.shuqi.model.manager.FreeBookDownloadManager.DownConstant;
import com.shuqi.model.manager.TxtDownLoadManager;
import com.shuqi.model.manager.TxtDownLoadManager.DownStateListener;
import com.shuqi.model.net.HttpFactory;

/**
 * 
 * 
 * @author <a href="mailto:">yaozhen</a>
 * @version 2014-2-17下午7:26:06
 */
public class BookDownloadActivity extends ActivityBase implements OnClickListener,
        DownStateListener, OnItemLongClickListener, OnItemClickListener {

    public final static String TAG = "BookDownloadActivity";

    private ListView mListView;

    private View mEmptyView;

    private BookDownloadAdapter mAdapter;

    private List<TxtDownload> mList = new ArrayList<TxtDownload>();

    private BottomDialog mDelDialog;

    private TextView mDelDialogTitle;

    private View mDelDialogCancle;

    private View mDelDialogConfirm;

    private Dialog mNetworkDialog;

    private TxtDownload mCurDownInfo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_book_download);
        init();
        loadData();
    }

    private void init() {
        mListView = (ListView) findViewById(R.id.book_download_listView);
        mEmptyView = findViewById(R.id.book_down_empty);
        mAdapter = new BookDownloadAdapter();
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
        mListView.setOnItemLongClickListener(this);
        findViewById(R.id.webkit_top_back).setOnClickListener(this);
    }

    // 从数据库加载数据
    private void loadData() {
        mList = TxtDownloadDao.getInstance().getTxtDownloadList();
        updateUI();
    }

    private void updateUI() {
        mAdapter.setData(mList);
        if (mList == null || mList.size() == 0) {
            mEmptyView.setVisibility(View.VISIBLE);
        } else {
            mEmptyView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.webkit_top_back:
                ActivityManager.getInstance().bottomFinishActivity(this);
                break;
            case R.id.dialog_bookdown_del_cancel_tv:
                hideBottomDelDialog();
                break;
            case R.id.dialog_cancel_tv:
                hideNetWorkDialog();
                break;
            case R.id.dialog_confirm_tv:
                hideNetWorkDialog();
                if (!isNetWorkAvailable()) {
                    showMsg("请检查您的网络");
                    return;
                }
                NetNotify.getInstance().changeNotifyState(NetNotify.DOWNLOAD_BOOK_OFFLINE);
                TxtDownLoadManager.getInstance().retryDownload(mCurDownInfo);
                break;
            default:
                break;
        }
    }

    @Override
    public void activityLogicForward() {

    }

    @Override
    public void activityInitData() {

    }

    private void showNetWorkDialog() {
        if (mNetworkDialog == null) {
            View view = getLayoutInflater().inflate(R.layout.view_dialog_network, null);
            view.findViewById(R.id.dialog_cancel_tv).setOnClickListener(this);
            view.findViewById(R.id.dialog_confirm_tv).setOnClickListener(this);
            mNetworkDialog = new Dialog(this, R.style.net_dialog);
            LayoutParams params =
                    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            mNetworkDialog.addContentView(view, params);
            mNetworkDialog.setCanceledOnTouchOutside(true);
        }
        mNetworkDialog.show();
    }

    private void hideNetWorkDialog() {
        if (mNetworkDialog != null && mNetworkDialog.isShowing()) {
            mNetworkDialog.dismiss();
        }
    }

    private boolean isShowNetWorkDialog() {
        boolean isNoWifi =
                NetNotify.getInstance().isNeedNotifyNoWifi(NetNotify.DOWNLOAD_BOOK_OFFLINE);
        return isNoWifi;
    }

    private boolean isFileExist(String filePath) {
        boolean ret = true;
        if (TextUtils.isEmpty(filePath)) {
            ret = false;
        } else {
            try {
                File f = new File(filePath);
                if (!f.exists()) {
                    ret = false;
                }
            } catch (Exception e) {
                ret = false;
                e.printStackTrace();
            }
        }
        return ret;
    }

    // 去阅读页面
    private void gotoBookReadPage(TxtDownload info) {
        if (info == null || TextUtils.isEmpty(info.getFilePath())) {
            return;
        }
        String filePath = info.getFilePath() + "/" + info.getBookId() + "/" + info.getFileName();
        if (isFileExist(filePath)) {
            EnterBookContent.jumpToBookContentByFilePath(this, filePath,-1);
        } else {
            showMsg("书籍已删除");
        }
    }

    // 下载一本书
    private void downLoadBook(TxtDownload info) {
        Log4an.v(TAG, "-----downLoadBook-----info is null=" + (info == null ? true : false));
        if (info == null) {
            return;
        }
        if (!isNetWorkAvailable()) {
            showMsg("请检查您的网络");
            return;
        }
        mCurDownInfo = info;
        boolean isShow = isShowNetWorkDialog();
        if (!isShow) {
            TxtDownLoadManager.getInstance().retryDownload(info);
        } else {
            showNetWorkDialog();
        }
    }

    private boolean isNetWorkAvailable() {
        int netType = HttpFactory.getApnType(this);
        return netType != HttpFactory.NOT_EXIST;
    }

    // 删除书籍
    private void delBook(TxtDownload info) {
        if (info == null) {
            return;
        }
        // 删除内存
        if (mList != null && mList.contains(info)) {
            mList.remove(info);
            updateUI();
        }
        TxtDownloadDao.getInstance().deleteTxtDownloadInfo(info.getBookId(), info.getDownloadUrl());
        // 停止下载以及删除数据库
        TxtDownLoadManager.getInstance().removeDownLoadBookTask(true, info.getDownKey(),
                info.getBookId(), info.getFileName());
        showMsg("删除成功");
    }

    // 显示删除的dialog
    private void showBottomDelDialog(final TxtDownload info) {
        if (info == null) {
            return;
        }
        if (mDelDialog == null) {
            View view = getLayoutInflater().inflate(R.layout.view_dialog_bottom_bookdown_del, null);
            mDelDialogTitle = (TextView) view.findViewById(R.id.dialog_bookdown_del_title_tv);
            mDelDialogCancle = view.findViewById(R.id.dialog_bookdown_del_cancel_tv);
            mDelDialogConfirm = view.findViewById(R.id.dialog_bookdown_del_confirm_tv);
            mDelDialogCancle.setOnClickListener(this);
            mDelDialog = new BottomDialog(this, view);
        }
        mDelDialogTitle.setText(info.getBookName());
        mDelDialogConfirm.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                hideBottomDelDialog();
                delBook(info);

                // 同步删除书架上的书签信息，因为是本地书籍，仅需要booktype和filepath即可
                final List<BookMarkInfo> markInfos = new ArrayList<BookMarkInfo>();
                BookMarkInfo markInfo = new BookMarkInfo();
                markInfo.setBookType(BookMarkInfo.TYPE_LOCAL_BOOKMARK);
                String filePath =
                        info.getFilePath() + "/" + info.getBookId() + "/" + info.getFileName();
                markInfo.setFilePath(filePath);
                markInfos.add(markInfo);
                BookMarkManager.getInstance().delBookMarks(markInfos, false);
            }
        });
        mDelDialog.show();
    }

    // 隐藏删除的dialog
    private void hideBottomDelDialog() {
        if (mDelDialog != null) {
            mDelDialog.dismiss();
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // 注册监听
        TxtDownLoadManager.getInstance().registerDownStateListener(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解注册监听
        TxtDownLoadManager.getInstance().unRegisterDownStateListener(this);

        if (mList != null) {
            mList.clear();
            mList = null;
        }

        if (mDelDialog != null) {
            mDelDialog.dismiss();
        }

        if (mAdapter != null) {
            mAdapter.onDestroy();
        }

        mCurDownInfo = null;
    }

    /***
     * 打开下载页
     * 
     * @param activity 最外层的Activity
     */
    public static void show(Activity activity) {
        Intent intent = new Intent(activity, BookDownloadActivity.class);
        // ActivityManager.getInstance().startNextActivity(intent, activity);
        ActivityManager.getInstance().startBottomNextActivity(intent, activity);
    }

    @Override
    public void updateDownState(final String bookDownKey, final int state, final long loadSize,
            final long totalSize, final String msg) {
        if (totalSize == 0) {
            return;
        }
        Runnable r = new Runnable() {

            @Override
            public void run() {
                switch (state) {
                    case DownConstant.STATE_ERROR:
                        if (!TextUtils.isEmpty(msg)) {
                            showMsg(msg);// 下载失败，请检查您的网络
                        } else {
                            showMsg("下载失败");
                        }
                        break;
                    default:
                        break;
                }
                mAdapter.updateBookStateUI(bookDownKey, state, loadSize, totalSize);
            }
        };

        ShuqiApplication.getApplicationHandler().post(r);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (mList != null && mList.size() > position) {
            showBottomDelDialog(mList.get(position));
        }

        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().bottomFinishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mList != null && position >= 0 && position < mList.size()) {
            final TxtDownload info = mList.get(position);
            int state = info.getDownloadStatus();
            switch (state) {
                case DownConstant.STATE_FINISH:
                    gotoBookReadPage(info);
                    break;
                case DownConstant.STATE_READY:
                case DownConstant.STATE_ERROR:
                    downLoadBook(info);
                    break;
                default:
                    break;
            }
        }

    }
}
